package mo.leetcode_hot;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;

@SuppressWarnings("Duplicates")
public class L3 {

    public int lengthOfLongestSubstring(String s) {
        int n = s.length();
        if (n <= 1) {
            return n;
        }
        Map<Character, Integer> char2index = new HashMap<>();
        char2index.put(s.charAt(0), 0);
        int max = 1;
        int start = 0;
        for (int i = 1; i < n; i++) {
            if (!char2index.containsKey(s.charAt(i))) {
                max = Math.max(max, i-start+1);
            } else {
                int last = char2index.get(s.charAt(i));
                if (last < start) {
                    max = Math.max(max, i-start+1);
                } else {
                    start = last+1;
                }
            }
            char2index.put(s.charAt(i), i);
        }
        return max;
    }



    public int lengthOfLongestSubstring2(String s) {
        int max = 0;
        Queue<Character> queue = new LinkedList<>();
        for (char c : s.toCharArray()) {
            if (queue.contains(c)) {
                max = Math.max(max, queue.size());
                while (!queue.isEmpty()) {
                    if (queue.poll() == c) {
                        break;
                    }
                }
            }
            queue.add(c);
        }
        return Math.max(max, queue.size());
    }

    public static void main(String[] args) {
        L3 test = new L3();
        System.out.println(test.lengthOfLongestSubstring("dvdf"));
    }

}
